package com.suneast.suneaststore.modules.personal.order.fragment;

import android.Manifest;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.bean.personal.address.AddressBean;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.common.entity.Picture;
import com.suneast.suneaststore.modules.personal.address.AddressListFragment;
import com.suneast.suneaststore.modules.personal.order.OrderHandler;
import com.suneast.suneaststore.modules.personal.order.adapter.CustomizePhotoAdapter;
import com.suneast.suneaststore.modules.personal.order.event.CustomizeResult;
import com.suneast.suneaststore.ui.fragments.BaseFragmentWithDialog;
import com.suneast.suneaststore.util.net.upload.ResultEvent;
import com.suneast.suneaststore.util.net.upload.UploadHandler;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.noobie.photopicker.common.Global;
import org.noobie.photopicker.entity.Photo;
import org.noobie.photopicker.ui.PhotoPickerFragment;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class FastOrderMaker extends BaseFragmentWithDialog implements CustomizePhotoAdapter.OnItemChangedListener {
    private final static String TAG = FastOrderMaker.class.getSimpleName();
    private final static int RequestCode = TAG.hashCode();
    @BindView(R.id.title_bar)
    TextView title;

    @BindView(R.id.rv_photo_group)
    RecyclerView rvPhotoGroup;

    @BindView(R.id.shipping_address)
    TextView tvAddress;
    @BindView(R.id.shipping_address_choice)
    TextView tvAddrChoice;

    @BindView(R.id.edit_requirements)
    EditText edtRequirements;

    @OnClick(R.id.ib_return_back)
    void onBackPressed() {
        pop();
    }

    private int merchId = 0;
    private int addressId = -1;

    private CustomizePhotoAdapter adapter;

    @NeedsPermission({Manifest.permission.READ_EXTERNAL_STORAGE})
    void startPickerFragment() {
        PhotoPickerFragment fragment = new PhotoPickerFragment();
        Bundle arguments = new Bundle();
        arguments.putInt(Global.Def.KEY_MAX, adapter.remaining());
        fragment.setArguments(arguments);
        startForResult(fragment, RequestCode);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        FastOrderMakerPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_fast_order;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        title.setText(R.string.fast_order);
        if (savedInstanceState != null) {
            merchId = savedInstanceState.getInt("merchid", 0);
        } else {
            Bundle arguments = getArguments();
            if (arguments != null) {
                merchId = arguments.getInt("merchid", 0);
            }
        }
        rvPhotoGroup.setLayoutManager(new GridLayoutManager(getContext(), 3));
        adapter = new CustomizePhotoAdapter();
        rvPhotoGroup.setAdapter(adapter);
        adapter.refreshAll();

        EventBus.getDefault().register(this);
        adapter.setOnItemChangedListener(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("merchid", merchId);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
        for (int i = 0, len = adapter.available(); i < len; i++) {
            Picture picture = adapter.getItem(i);
            if (picture.getState() == Picture.State.UPLOADING) {
                UploadHandler.cancel(picture.getKey());
            }
        }
    }

    @Override
    public void onFragmentResult(int requestCode, int resultCode, Bundle data) {
        super.onFragmentResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == RequestCode) {
                List<Photo> photoList = data.getParcelableArrayList("photos");
                if (photoList != null)
                    for (int i = 0, len = photoList.size(); i < len; i++) {
                        File file = new File(photoList.get(i).getFilePath());
                        if (adapter.remaining() > 0) {
                            String key = UploadHandler.generateKey(file);
                            adapter.addItem(file.getPath(), key);
                            UploadHandler.upload(file, key);
                        }
                    }
            } else if (requestCode == RequestCode + 1) {
                AddressBean addressBean = data.getParcelable("address_bean");
                if (addressBean != null) {
                    addressId = addressBean.getId();
                    tvAddrChoice.setVisibility(View.INVISIBLE);
                    tvAddress.setVisibility(View.VISIBLE);
                    tvAddress.setText(Html.fromHtml(getString(R.string.shipping_address, addressBean.getRealname(), addressBean.getMobile(),
                            addressBean.getProvince(), addressBean.getCity(), addressBean.getArea(), addressBean.getTown(), addressBean.getAddress())));
                }
            }
        }
    }

    @Override
    public void onCancel(String key) {
        UploadHandler.cancel(key);
    }

    @Override
    public void onAdd(int position) {
        // 目前界面操作逻辑暂时用不着position
        FastOrderMakerPermissionsDispatcher.startPickerFragmentWithPermissionCheck(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onUploadResult(ResultEvent result) {
        adapter.notifyItemUploaded(result.getValue() == Flag.Result.SUCCEED, result.getKey());
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOrderOperateResult(CustomizeResult result) {
        Log.e("test", "onOrderOperateResult: value = " + result.getValue());
        if (result.getValue() == 1) {
            // 跳转订单管理
            startWithPop(new PurchaseManage().withId(R.id.tv_all_order));
        } else {
            setDialogStyle(HIDE_DIALOG_TITLE | HIDE_DIALOG_CANCEL);
            setDialogContent("订单提交失败");
            showDialog();
        }
    }

    @OnClick({R.id.shipping_address_choice, R.id.shipping_address, R.id.btn_commit})
    void onClick(View v) {
        switch (v.getId()) {
            case R.id.shipping_address:
            case R.id.shipping_address_choice:
                AddressListFragment fragment = new AddressListFragment();
                Bundle arguments = new Bundle();
                arguments.putInt(AddressListFragment.KEY_TYPE, 1);
                fragment.setArguments(arguments);
                startForResult(fragment, RequestCode + 1);
                break;
            case R.id.btn_commit:
                if (addressId == -1) {
                    setDialogStyle(HIDE_DIALOG_TITLE | HIDE_DIALOG_CANCEL);
                    setDialogContent("请填写地址");
                    showDialog();
                    break;
                }
                if (edtRequirements.getText().toString().isEmpty()) {
                    setDialogStyle(HIDE_DIALOG_TITLE | HIDE_DIALOG_CANCEL);
                    setDialogContent("请填写订单需求");
                    showDialog();
                    break;
                }
                if (adapter.available() == 0) {
                    setDialogStyle(HIDE_DIALOG_TITLE | HIDE_DIALOG_CANCEL);
                    setDialogContent("请至少选择一张图片");
                    showDialog();
                    break;
                }
                if (adapter.isUploading()) {
                    setDialogStyle(HIDE_DIALOG_TITLE | HIDE_DIALOG_CANCEL);
                    setDialogContent("请等待图片上传完毕");
                    showDialog();
                    break;
                }
                List<String> imgs = new ArrayList<>();
                for (int i = 0, len = adapter.available(); i < len; i++) {
                    imgs.add(adapter.getItem(i).getKey());
                }
                String imgsJsonStr = JSON.toJSONString(imgs);
                OrderHandler.submitFastOrder(edtRequirements.getText().toString(),
                        addressId, merchId, imgsJsonStr);
                break;
        }
    }
}
